'''
Created on Feb 22, 2014

@author: yfrank
'''

import CodingUtils.Logging as Logging

class PeerTable(object):
    '''
    classdocs
    '''

    def __init__(self):
        self.peer_map = {}

    def add_peer(self,peer,addr):
        if addr in self.peer_map:
            Logging.log("Already had Peer: "+str(peer))
        else:
            Logging.log("Adding Peer: "+str(peer))
            self.peer_map[addr] = peer

    def get_peer(self,addr):
        if addr in self.peer_map:
            return self.peer_map[addr]
        else: return None

    def remove_peer(self,addr):
        peer = self.peer_map[addr]
        peer.disconnect()
        Logging.log("Removing Peer: "+str(peer))
        del self.peer_map[addr]

    def get_peer2socket_map(self):
        ret = {}
        for peer in self.peer_map.values():
            if peer.isClosed(): continue
            soc = peer.get_channel().socket()
            ret[soc] = peer
        return ret
